

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="xuehaoweng">
  <meta name="keywords" content="">
  
    <meta name="description" content="APIKEY 的设计与使用 一、APIKEY 的生成与存储 随机生成 APIKEY：常用的方法是使用随机字符串生成器或数据加密方法生成字符串，确保每个 APIKEY 都是唯一的。 存储：APIKEY 可以存储在数据库中，但为了安全起见，通常会使用加密的方式存储。  二、APIKEY 的传递 在请求头中传递：大多数情况下，APIKEY 会作为请求头的一部分发送。 请求参数：在某些情况下，APIKEY">
<meta property="og:type" content="article">
<meta property="og:title" content="Python项目单独设置API-KEY">
<meta property="og:url" content="http://blog.xhweng.cn/2024/01/05/python_API-KEY/index.html">
<meta property="og:site_name" content="有追求的开发者">
<meta property="og:description" content="APIKEY 的设计与使用 一、APIKEY 的生成与存储 随机生成 APIKEY：常用的方法是使用随机字符串生成器或数据加密方法生成字符串，确保每个 APIKEY 都是唯一的。 存储：APIKEY 可以存储在数据库中，但为了安全起见，通常会使用加密的方式存储。  二、APIKEY 的传递 在请求头中传递：大多数情况下，APIKEY 会作为请求头的一部分发送。 请求参数：在某些情况下，APIKEY">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.xhweng.cn/img/file_img/key.jpg">
<meta property="article:published_time" content="2024-01-05T01:45:40.000Z">
<meta property="article:modified_time" content="2024-04-03T08:12:09.428Z">
<meta property="article:author" content="xuehaoweng">
<meta property="article:tag" content="编程">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://blog.xhweng.cn/img/file_img/key.jpg">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Python项目单独设置API-KEY - 有追求的开发者</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"blog.xhweng.cn","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"b3bbb822b3d2a5e2761107c03cf72b8c","google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?b3bbb822b3d2a5e2761107c03cf72b8c";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  



  
<meta name="generator" content="Hexo 7.0.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>有追求的开发者</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Python项目单独设置API-KEY"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-01-05 09:45" pubdate>
          2024年1月5日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          1k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          9 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Python项目单独设置API-KEY</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="APIKEY-的设计与使用"><a href="#APIKEY-的设计与使用" class="headerlink" title="APIKEY 的设计与使用"></a><strong>APIKEY 的设计与使用</strong></h2><p><img src="https://self-bucket-1258377547.cos.ap-shanghai.myqcloud.com/picgo-test/cc6619482f68483bd738c264112c3721.jpg" srcset="/img/loading.gif" lazyload alt="KEY"></p>
<h2 id="一、APIKEY-的生成与存储"><a href="#一、APIKEY-的生成与存储" class="headerlink" title="一、APIKEY 的生成与存储"></a>一、APIKEY 的生成与存储</h2><ol>
<li>随机生成 APIKEY：常用的方法是使用随机字符串生成器或数据加密方法生成字符串，确保每个 APIKEY 都是唯一的。</li>
<li>存储：APIKEY 可以存储在数据库中，但为了安全起见，通常会使用加密的方式存储。</li>
</ol>
<h3 id="二、APIKEY-的传递"><a href="#二、APIKEY-的传递" class="headerlink" title="二、APIKEY 的传递"></a>二、APIKEY 的传递</h3><ol>
<li>在请求头中传递：大多数情况下，APIKEY 会作为请求头的一部分发送。</li>
<li>请求参数：在某些情况下，APIKEY 也可以作为请求参数的一部分。但这种方法不安全，因为请求参数容易被记录或查看。</li>
</ol>
<h3 id="三、APIKEY-的使用限制"><a href="#三、APIKEY-的使用限制" class="headerlink" title="三、APIKEY 的使用限制"></a>三、APIKEY 的使用限制</h3><ol>
<li>限制 IP 地址：可以为 APIKEY 设置允许的 IP 地址范围，增加安全性。（在模型中设置字段，访问接口做验证）</li>
<li>限制使用频率：可以设置 API 请求的频率限制，防止被滥用。（设置频率字段，接口验证频率次数）</li>
<li>有效期限制：为 APIKEY 设置有效期，过期后需要重新生成。（设置过期时间）</li>
</ol>
<h3 id="四、APIKEY-的作用"><a href="#四、APIKEY-的作用" class="headerlink" title="四、APIKEY 的作用"></a>四、APIKEY 的作用</h3><ol>
<li>身份验证：APIKEY 可用于验证请求者的身份。</li>
<li>授权控制：基于 APIKEY 可以控制哪些用户或系统可以访问特定的 API。</li>
<li>跟踪和分析：APIKEY 可以用于分析请求的数据，例如流量、使用情况等。</li>
<li>安全保护：APIKEY 增加了非法访问的难度，减少了未经授权的访问。</li>
</ol>
<h3 id="五、注意事项"><a href="#五、注意事项" class="headerlink" title="五、注意事项"></a>五、注意事项</h3><ol>
<li>不要在客户端代码中硬编码 APIKEY，因为这样会导致安全风险。</li>
<li>定期审查和更新 APIKEY，确保其安全性和有效性。</li>
<li>对于不再使用的 APIKEY，应及时删除或使其失效。</li>
<li>使用 HTTPS 协议来传输 API 请求和数据，确保数据的安全性。</li>
</ol>
<h2 id="在-Django-框架中如何实现单独设置-APIKEY"><a href="#在-Django-框架中如何实现单独设置-APIKEY" class="headerlink" title="在 Django 框架中如何实现单独设置 APIKEY"></a>在 Django 框架中如何实现单独设置 APIKEY</h2><h3 id="新建-APIKEY-模型"><a href="#新建-APIKEY-模型" class="headerlink" title="新建 APIKEY 模型"></a>新建 APIKEY 模型</h3><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs routeros">class ApiKeyToken(models.Model):<br>    key = models.CharField(<span class="hljs-attribute">max_length</span>=40, <span class="hljs-attribute">primary_key</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">verbose_name</span>=<span class="hljs-string">&#x27;key&#x27;</span>)<br>    platform = models.CharField(<span class="hljs-attribute">max_length</span>=40, <span class="hljs-attribute">verbose_name</span>=<span class="hljs-string">&#x27;api-key运用平台&#x27;</span>, <span class="hljs-attribute">default</span>=<span class="hljs-string">&#x27;netops&#x27;</span>)<br>    is_active = models.BooleanField(<span class="hljs-attribute">default</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">verbose_name</span>=<span class="hljs-string">&#x27;状态&#x27;</span>)<br>    lastGetTime = models.DateTimeField(<span class="hljs-attribute">blank</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">auto_now</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">null</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">verbose_name</span>=<span class="hljs-string">&#x27;最近查询时间&#x27;</span>)<br>    expireTime = models.DateTimeField(<span class="hljs-attribute">blank</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">auto_now</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">null</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">verbose_name</span>=<span class="hljs-string">&#x27;key过期时间&#x27;</span>)<br>    countTimes = models.IntegerField(<span class="hljs-attribute">blank</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">null</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">verbose_name</span>=<span class="hljs-string">&#x27;key使用次数&#x27;</span>)<br>    serverIp = models.CharField(<span class="hljs-attribute">blank</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">null</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">verbose_name</span>=<span class="hljs-string">&#x27;key提供服务的IP或IP范围&#x27;</span>,max_length=100)<br><br>    def save(self, <span class="hljs-number">*a</span>rgs, **kwargs):<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> self.key:<br>            self.key = self.generate_key()<br>        return super(ApiKeyToken, self).save(<span class="hljs-number">*a</span>rgs, **kwargs)<br><br>    def generate_key(self):<br>        return binascii.hexlify(os.urandom(20)).decode()<br><br>    def __unicode__(self):<br>        return self.key<br><br>    class Meta:<br>        # abstract = <span class="hljs-literal">True</span><br>        db_table = <span class="hljs-string">&#x27;apikey_model&#x27;</span>  # 通过db_table自定义数据表名<br>        verbose_name = _(<span class="hljs-string">&#x27;ApiKey&#x27;</span>)<br>        verbose_name_plural = _(<span class="hljs-string">&#x27;ApiKey&#x27;</span>)<br><br><br></code></pre></td></tr></table></figure>

<h3 id="执行数据迁移"><a href="#执行数据迁移" class="headerlink" title="执行数据迁移"></a>执行数据迁移</h3><figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs vim"><span class="hljs-keyword">python</span> manage.<span class="hljs-keyword">py</span> makemigrations<br><br><span class="hljs-keyword">python</span> manage.<span class="hljs-keyword">py</span> migrate<br><br></code></pre></td></tr></table></figure>

<p><img src="https://self-bucket-1258377547.cos.ap-shanghai.myqcloud.com/picgo-test/640.png" srcset="/img/loading.gif" lazyload alt="迁移记录"></p>
<h3 id="使用-APIKEY-模型"><a href="#使用-APIKEY-模型" class="headerlink" title="使用 APIKEY 模型"></a>使用 APIKEY 模型</h3><h4 id="生成APIKEY"><a href="#生成APIKEY" class="headerlink" title="生成APIKEY"></a><strong>生成APIKEY</strong></h4><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs stylus"><br>api_key_token = <span class="hljs-built_in">ApiKeyToken</span>()<br>api_key_token<span class="hljs-selector-class">.key</span> = api_key_token<span class="hljs-selector-class">.generate_key</span>()<br>api_key_token<span class="hljs-selector-class">.save</span>()<br><br></code></pre></td></tr></table></figure>
<h4 id="使用APKEY"><a href="#使用APKEY" class="headerlink" title="使用APKEY"></a><strong>使用APKEY</strong></h4><p>新建验证类 auth.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> rest_framework.authentication <span class="hljs-keyword">import</span> TokenAuthentication, get_authorization_header<br><span class="hljs-keyword">from</span> rest_framework.exceptions <span class="hljs-keyword">import</span> AuthenticationFailed<br><br><span class="hljs-keyword">from</span> open_ipam.models <span class="hljs-keyword">import</span> ApiKeyToken<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">ApiKeyAuthentication</span>(<span class="hljs-title class_ inherited__">TokenAuthentication</span>):<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">get_token_from_auth_header</span>(<span class="hljs-params">self, auth</span>):<br>        auth = auth.split()<br>        <span class="hljs-comment"># print(auth)</span><br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> auth <span class="hljs-keyword">or</span> auth[<span class="hljs-number">0</span>].lower() != <span class="hljs-string">b&#x27;api-key&#x27;</span>:<br>            <span class="hljs-keyword">return</span> AuthenticationFailed(<span class="hljs-string">&#x27;Invalid api-key header. No credentials provided.&#x27;</span>)<br><br>        <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(auth) == <span class="hljs-number">1</span>:<br>            <span class="hljs-keyword">raise</span> AuthenticationFailed(<span class="hljs-string">&#x27;Invalid api-key header. No credentials provided.&#x27;</span>)<br>        <span class="hljs-keyword">elif</span> <span class="hljs-built_in">len</span>(auth) &gt; <span class="hljs-number">2</span>:<br>            <span class="hljs-keyword">raise</span> AuthenticationFailed(<span class="hljs-string">&#x27;Invalid api-key header. Token string should not contain spaces.&#x27;</span>)<br><br>        <span class="hljs-keyword">try</span>:<br>            <span class="hljs-keyword">return</span> auth[<span class="hljs-number">1</span>].decode()<br>        <span class="hljs-keyword">except</span> UnicodeError:<br>            <span class="hljs-keyword">raise</span> AuthenticationFailed(<span class="hljs-string">&#x27;Invalid api-key header. Token string should not contain invalid characters.&#x27;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">authenticate</span>(<span class="hljs-params">self, request</span>):<br>        auth = get_authorization_header(request)<br>        token = self.get_token_from_auth_header(auth)<br><br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> token:<br>            token = request.GET.get(<span class="hljs-string">&#x27;api-key&#x27;</span>, request.POST.get(<span class="hljs-string">&#x27;api-key&#x27;</span>, <span class="hljs-literal">None</span>))<br><br>        <span class="hljs-keyword">if</span> token:<br>            <span class="hljs-keyword">return</span> self.authenticate_credentials(token)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">authenticate_credentials</span>(<span class="hljs-params">self, key</span>):<br>        <span class="hljs-keyword">try</span>:<br>            token = ApiKeyToken.objects.get(key=key)<br>        <span class="hljs-keyword">except</span> ApiKeyToken.DoesNotExist:<br>            <span class="hljs-keyword">raise</span> AuthenticationFailed(<span class="hljs-string">&#x27;Invalid Api key.&#x27;</span>)<br><br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> token.is_active:<br>            <span class="hljs-keyword">raise</span> AuthenticationFailed(<span class="hljs-string">&#x27;Api key inactive or deleted.&#x27;</span>)<br><br>        <span class="hljs-comment"># user = token.company.users.first()  # what ever you want here</span><br>        <span class="hljs-keyword">return</span> token<br><br></code></pre></td></tr></table></figure>
<h4 id="新建装饰器"><a href="#新建装饰器" class="headerlink" title="新建装饰器"></a>新建装饰器</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">check_api_key</span>(<span class="hljs-params">func</span>):<br>    auth_check = ApiKeyAuthentication()<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">wrap</span>(<span class="hljs-params">view, request</span>):<br>        <span class="hljs-keyword">if</span> request.headers[<span class="hljs-string">&#x27;Authorization&#x27;</span>]:<br>            <span class="hljs-keyword">if</span> <span class="hljs-string">&#x27;api-key&#x27;</span> <span class="hljs-keyword">in</span> request.headers[<span class="hljs-string">&#x27;Authorization&#x27;</span>]:<br>                auth_check.authenticate(request)<br>                <span class="hljs-keyword">return</span> func(view, request)<br>            <span class="hljs-keyword">else</span>:<br>                <span class="hljs-keyword">raise</span> AuthenticationFailed(<span class="hljs-string">&#x27;Invalid api-key header. No credentials provided.&#x27;</span>)<br>        <span class="hljs-keyword">raise</span> <span class="hljs-string">&quot;Invalid Api key&quot;</span><br><br>    <span class="hljs-keyword">return</span> wrap<br><br></code></pre></td></tr></table></figure>

<h4 id="使用装饰器"><a href="#使用装饰器" class="headerlink" title="使用装饰器"></a>使用装饰器</h4><figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs angelscript"><span class="hljs-keyword">class</span> <span class="hljs-symbol">IpamOpenAPI</span>(<span class="hljs-symbol">APIView</span>):<br>    @<span class="hljs-symbol">check_api_key</span><br>    <span class="hljs-symbol">def</span> <span class="hljs-symbol">post</span>(<span class="hljs-symbol">self, <span class="hljs-symbol">request</span></span>):<br>        <span class="hljs-symbol">pass</span><br></code></pre></td></tr></table></figure>

<p>如此用户请求当前View时候，则会先经过装饰器进行APIKEY的校验。在视图函数中，我们首先从请求头中获取APIKEY，然后查询数据库验证APIKEY的有效性。如果APIKEY无效或缺失，我们返回相应的错误响应。如果APIKEY有效，则继续处理请求。</p>
<p>目前实现的APIKEY校验方式仅仅是一种类型，需要注意的是，在实际应用中，应该使用更加安全的方式来存储和验证APIKEY，例如使用加密的存储方式、引入更强大的身份验证机制等。此外，还应该考虑其他的安全措施，例如限制API的访问频率、限制IP地址等</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E7%BC%96%E7%A8%8B/" class="category-chain-item">编程</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E7%BC%96%E7%A8%8B/" class="print-no-link">#编程</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Python项目单独设置API-KEY</div>
      <div>http://blog.xhweng.cn/2024/01/05/python_API-KEY/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>xuehaoweng</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年1月5日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/03/27/%E4%BA%91%E5%8E%9F%E7%94%9F%E7%9B%91%E6%8E%A7%E5%85%A5%E9%97%A8%EF%BC%9A%E4%BD%BF%E7%94%A8Prometheus%E3%80%81Alertmanager%20%E5%AE%9E%E7%8E%B0Cpu%E5%92%8C%E5%86%85%E5%AD%98%E7%9A%84%E7%9B%91%E6%8E%A7%E5%91%8A%E8%AD%A6/" title="云原生监控入门：使用Prometheus、Alertmanager 实现Cpu和内存的监控告警">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">云原生监控入门：使用Prometheus、Alertmanager 实现Cpu和内存的监控告警</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2024/01/05/python_language_desc/" title="python语言介绍">
                        <span class="hidden-mobile">python语言介绍</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      皖ICP备2024038809号-2
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="/img/police_beian.png" srcset="/img/loading.gif" lazyload alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
